// 全局错误处理中间件
export const errorHandler = (err, req, res, next) => {
  // 默认错误状态码为500
  const statusCode = err.statusCode || 500;
  
  // 简化错误栈信息
  let simplifiedStack = null;
  if (process.env.NODE_ENV === 'development') {
    // 只保留"ApiError: 错误消息"的格式
    simplifiedStack = `${err.name}: ${err.message}`;
  }
  
  // 开发环境下返回简化错误信息，生产环境下只返回消息
  const response = {
    message: err.message || '服务器内部错误',
    status: statusCode,
    ...(process.env.NODE_ENV === 'development' && {
      stack: simplifiedStack,
      path: req.path
    })
  };
  
  // 记录错误
  console.error(`[${new Date().toISOString()}] 错误: ${err.message}`);
  
  // 发送错误响应
  res.status(statusCode).json(response);
};

// 404错误处理中间件
export const notFoundHandler = (req, res, next) => {
  const error = new Error(`找不到 - ${req.originalUrl}`);
  error.statusCode = 404;
  next(error);
};

// 自定义API错误类
export class ApiError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
    this.name = this.constructor.name;
    Error.captureStackTrace(this, this.constructor);
  }
  
  static badRequest(message = '请求无效') {
    return new ApiError(message, 400);
  }
  
  static unauthorized(message = '未授权') {
    return new ApiError(message, 401);
  }
  
  static forbidden(message = '禁止访问') {
    return new ApiError(message, 403);
  }
  
  static notFound(message = '资源不存在') {
    return new ApiError(message, 404);
  }
  
  static conflict(message = '资源冲突') {
    return new ApiError(message, 409);
  }
  
  static internal(message = '服务器内部错误') {
    return new ApiError(message, 500);
  }
}

// 异步函数错误捕获包装器
export const asyncHandler = (fn) => {
  return (req, res, next) => {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
}; 